<template>
  <el-dialog title="引入工序" :visible.sync="show" :close-on-click-modal="false" :show-close="!btnLoading" width="1200px" @closed="closed">
    <el-row :gutter="20">
      <el-col :span="4">
        <div class="subtitle">阶段</div>
        <el-scrollbar style="height: 500px" v-loading="checkTypeLoading">
          <el-tree ref="tree" :data="checkTypeList" :props="{ label: 'typeName' }" node-key="typeId" highlight-current default-expand-all @node-click="handleNodeClick" />
        </el-scrollbar>
      </el-col>
      <el-col :span="20">
        <el-table ref="table" v-loading="listLoading" :data="list" size="small" row-key="tableId" default-expand-all height="530px" @row-click="rowClick" @selection-change="onSelect" @select="checkboxSelect" @select-all="selectAll">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="工序编码" prop="tableCode" show-overflow-tooltip min-width="150" />
          <el-table-column label="工序名称" prop="tableName" show-overflow-tooltip min-width="200" />
          <el-table-column label="验收对象" prop="unitType" align="center" min-width="80">
            <span slot-scope="{ row }">{{ row.unitType | selectEnumLabel(unitTypeEnum) }}</span>
          </el-table-column>
          <el-table-column label="工程师验收比例（%）" prop="gcsPercent" align="center" min-width="120" />
          <el-table-column label="监理验收比例（%）" prop="jlPercent" align="center" min-width="120" />
          <el-table-column label="项目总验收比例（%）" prop="xmzPercent" align="center" min-width="120" />
          <el-table-column label="项目经理验收比例（%）" prop="xmjlPercent" align="center" min-width="130" />
          <el-table-column label="专业类别" align="center" min-width="70">
            <dict-tag slot-scope="{ row }" :options="specialTypes" :value="row.specialTypeId" />
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <div slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 批量添加楼栋工序
import { debounce, flatList2tree, removeEmptyArray } from '@/utils'
import { getSpecialTypes } from '@/utils/dict/custom'
import { getEnum } from '@/api/common'
import { listCheckType, listCheckTable, addCheckConfigBatch } from '@/api/qualityManage/cq'
export default {
  name: 'BatchAddCheckConfig',
  props: { value: { type: Boolean, default: false } },
  data() {
    return {
      btnLoading: false,
      checkTypeLoading: false,
      listLoading: false,
      list: [], // 工序树形数据
      queryParams: { typeId: '' },
      selected: [],
      building: {},
      checkConfigList: [], // 楼栋已配置工序
      checkTypeList: [], // 阶段
      unitTypeEnum: [], // 验收对象
      specialTypes: [] // 专业类别
    }
  },
  computed: {
    show: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    this.btnSubmit = debounce(this.onSubmit, 1e3, true)
    getEnum('unitType').then(res => (this.unitTypeEnum = res.data.unitType))
    getSpecialTypes().then(res => (this.specialTypes = res))
  },
  methods: {
    closed() {
      this.queryParams.typeId = ''
      this.$refs.tree.setCheckedKeys([])
    },
    open(building = {}, checkConfigList) {
      if (!building.id) return this.$message.warning('请选择楼栋')
      this.show = true
      this.building = building
      this.checkConfigList = checkConfigList || []
      this.getCheckTypeList()
      this.getList()
    },
    // 获取阶段
    async getCheckTypeList() {
      // if (this.checkTypeList.length) return
      this.checkTypeLoading = true
      const res = await listCheckType().catch(() => false)
      this.checkTypeLoading = false
      if (res === false) return

      const data = res.data || []
      this.checkTypeList = data
      // if (!data.length) return
      // this.queryParams.typeId = data[0].typeId
      // this.getList()
    },
    // 获取工序
    async getList() {
      this.listLoading = true
      const res = await listCheckTable(this.queryParams).catch(() => false)
      this.listLoading = false
      if (res === false) return

      let data = res.data || []
      data = flatList2tree(data, { id: 'tableId' })
      data = removeEmptyArray(data)
      this.list = data
    },
    // 左侧阶段点击
    handleNodeClick(item) {
      this.queryParams.typeId = item.typeId
      this.getList()
    },
    // 递归切换选中状态
    setChildren(children, checked) {
      children.map(row => {
        this.$refs.table.toggleRowSelection(row, checked)
        if (row.children) this.setChildren(row.children, checked)
      })
    },
    // 复选框点击，处理子节点状态
    checkboxSelect(selection, row) {
      // 修复 table 的复选行为滞后导致 selected 与 checked 对不上
      this.$nextTick(() => {
        const checked = selection.some(el => el.tableId === row.tableId)
        if (row.children) this.setChildren(row.children, checked)
      })
    },
    // 行点击
    rowClick(row) {
      this.$refs.table.toggleRowSelection(row)
      const checked = this.selected.some(el => el.tableId === row.tableId)
      if (row.children) this.setChildren(row.children, checked)
    },
    onSelect(val) {
      this.selected = val
    },
    // 全选
    selectAll(selection) {
      // 只要最外层第一个在 selection 里即全选
      const firstId = this.list[0]?.tableId || ''
      const checked = selection.some(el => el.tableId === firstId)
      if (!checked) return this.$refs.table.clearSelection()
      this.list.map(el => el.children && this.setChildren(el.children, checked))
    },
    async onSubmit() {
      const { building, checkConfigList, selected } = this
      const len = selected.length
      if (!building.id) return this.$message.warning('请选择楼栋')
      if (!len) return this.$message.warning('请选择工序')

      // 已配置工序
      const existIds = checkConfigList.map(i => i.checktableId)

      // 过滤出叶子结点，且未配置的工序
      const opts = selected
        .filter(i => i.isLeaf && !existIds.includes(i.tableId))
        .map(i => {
          const { tableId, ...temp } = i
          // tableId 改为 checktableId
          return {
            ...temp,
            checktableId: tableId,
            projectId: building.parentId,
            buildingId: building.id
          }
        })
      if (!opts.length) return this.$message.info('选中的工序已全部配置过')

      this.btnLoading = true
      const res = await addCheckConfigBatch(opts).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      this.msgSuccess('添加成功')
      this.show = false
      this.$emit('ok')
      this.$refs.table.clearSelection()
    }
  }
}
</script>
<style lang="scss" scoped>
.subtitle {
  font-size: 14px;
  color: #606266;
  padding: 0 0 10px 24px;
  border-bottom: 1px solid #dcdfe6;
}
</style>
